﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ViewModel.User;
using System.IO.IsolatedStorage;
using System.Windows.Navigation;
using GalaSoft.MvvmLight.Messaging;

namespace EPIClientRssWP7.WP7ViewModel
{
    public class AuthenticationNavEventArg : EventArgs
    {
        public bool IsConnected
        {get; set;}

        public AuthenticationNavEventArg(bool _connected)
        {
            IsConnected = _connected;
        }
    }

    public class WP7AuthenticationViewModel : AuthentificationViewModel
    {

        //private MainPage page;

        public WP7AuthenticationViewModel()
        {
            //RaiseAuthenticationNavEvent = new EventHandler<AuthenticationNavEventArg>();
        }


        public override bool NavigateToHome()
        {
            if (base.NavigateToHome() == true)
            {
                Messenger.Default.Send<string>("Home", "AuthenticationSwitch");
                //OnRaiseAuthenticationNavEvent(new AuthenticationNavEventArg(true));
                return true;
            }
            Messenger.Default.Send<string>("Auth", "AuthenticationSwitch");
            return false;
        }

        public static event EventHandler<AuthenticationNavEventArg> RaiseAuthenticationNavEvent;

        protected virtual void OnRaiseAuthenticationNavEvent(AuthenticationNavEventArg e)
        {
            EventHandler<AuthenticationNavEventArg> handler =  RaiseAuthenticationNavEvent;
            if (handler != null)
                handler(this, e);
        }

        public override void SaveId(string email, string password)
        {
            var store = IsolatedStorageSettings.ApplicationSettings;
            try
            {
                store.Add("email", email);
                store.Add("password", password);
            }
            catch (ArgumentNullException e)
            {
                return;
            }
            catch (ArgumentException e)
            {
                store.Remove("email");
                store.Remove("password");
                this.SaveId(email, password);
            }
        }

        public override bool GetId()
        {
            var store = IsolatedStorageSettings.ApplicationSettings;
            try
            {
                UserBind.email =(string) store["email"];
                UserBind.password = (string)store["password"];
                if (UserBind.email != null && UserBind.password != null)
                    return true;
                return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}
